package com.demo01;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

public class Demo03 {
    public static void main(String[] args) throws NoSuchFieldException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        //获取Class对象
        Class c = Person.class;

        //获取成员变量
        //多个变量
        Field[] fields = c.getDeclaredFields();
//        Field[] fields = c.getFields();
        for (Field field :
                fields) {
            System.out.println(field);
        }
        System.out.println("=================");
        //获取单个变量
        Field nameField = c.getField("name");
        System.out.println(nameField);

        Field addressField = c.getDeclaredField("address");
        System.out.println(addressField);

        //1.获取Class对象
        Class c1 = Class.forName("com.demo01.Person");
        //2.获取构造方法
        Constructor con = c1.getConstructor(String.class);
        //3.通过构造方法 创建对象
        Object obj = con.newInstance("小明");
        //4.获取指定的成员变量
        //public String name;
        Field nameField1 = c.getField("name");
        Field ageField1 = c.getField("age");
        Field addressField1 = c.getDeclaredField("address");
        addressField1.setAccessible(true);
        //5.通过方法 给指定对象的指定成员变量赋值或者获取值
        //获取值
        System.out.println("name = " + nameField1.get(obj));
        System.out.println("age = " + ageField1.get(obj));
        System.out.println("address = " + addressField1.get(obj));
        //赋值
        ageField1.set(obj, 22);
        nameField1.set(obj, "小红");
        addressField1.set(obj, "福建师范大学");
        System.out.println(obj);
    }
}
